namespace SubhadraSolutions.Sharp.Logging.LogSubscribers.Mail
{
    using SubhadraSolutions.Sharp.Utils;
    using System;
    using System.Collections.Generic;
    using System.Net.Mail;

    public class MailSubscriber : AbstractLogSubscriber
    {
        #region Constructors

        public MailSubscriber()
        {
            AlertMailIds = new List<string>();
        }

        #endregion Constructors

        #region Properties

        public List<string> AlertMailIds
        {
            get;
            set;
        }

        public IMailMessageBuilder MailMessageBuilder
        {
            get;
            set;
        }

        public string SendingMailId
        {
            get;
            set;
        }

        public string SmtpHost
        {
            get;
            set;
        }

        public string Subject
        {
            get;
            set;
        }

        #endregion Properties

        #region Methods

        protected override void initializeProtected()
        {
            base.initializeProtected();
            if (MailMessageBuilder == null)
            {
                throw new Exception("MailMessageBuilder must not be null");
            }
        }

        protected override void publishLogs(IEnumerable<LogStoreItem> e)
        {
            MailMessage message = MailMessageBuilder.BuildMessage(e);
            message.From = new MailAddress(SendingMailId);
            foreach (string mailId in AlertMailIds)
            {
                message.To.Add(mailId);
            }

            message.Subject = "[" + GlobalSettings.Instance.Environment + "] " + Subject;
            var client = new SmtpClient(SmtpHost) { UseDefaultCredentials = true };
            client.Send(message);
        }

        #endregion Methods
    }
}